package gl.util

import gl.window
import org.lwjgl.opengl.GL21C.*
import java.awt.image.BufferedImage
import java.nio.file.Files
import java.nio.file.Paths
import javax.imageio.ImageIO

object GLUtils {
    
    fun capture() {
        val output = Paths.get("D:\\lq\\gl", "screen.png")
        Files.createDirectories(output.parent)
        if (!Files.exists(output)) {
            val width = window.width
            val height = window.height
            val bufferSize = width * height * 4
            println("capture begin: $width x $height ($bufferSize)")
            val buffer = glGenBuffers()
            glBindBuffer(GL_PIXEL_PACK_BUFFER, buffer)
            glBufferData(GL_PIXEL_PACK_BUFFER, bufferSize.toLong(), GL_DYNAMIC_COPY)
            glPixelStorei(GL_PACK_ALIGNMENT, 1)
            glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
            glReadBuffer(GL_FRONT)
            glReadPixels(0, 0, width, height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, 0)
            val pixels = glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY)!!
            val image = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
            val array = IntArray(width * height)
            pixels.asIntBuffer()[array]
            image.setRGB(0, 0, width, height, array, 0, width)
            Files.createFile(output)
            ImageIO.write(image, "png", output.toFile())
            glUnmapBuffer(GL_PIXEL_PACK_BUFFER)
            glBindBuffer(GL_PIXEL_PACK_BUFFER, 0)
            println("capture end: $output")
        }
    }
}